package com.jinhua.huaojcodesandbox;


import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.jinhua.huaojcodesandbox.model.ExecuteMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class JavaDockerCodeSandBox extends JavaNativeCodeSandBoxTemplate {
    private static final long TIME_OUT = 5000l;

    private static Boolean FIRST_INIT = false;


    @Override
    public List<ExecuteMessage> runFile(File codeFile, List<String> inputList) {

        //创建执行docker的实例
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String image = "openjdk:8-alpine";

        if (FIRST_INIT) {
            FIRST_INIT = false;
//        拉去镜像
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
//        拉去镜像的回调函数
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                @Override
//        下载下一个时执行
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像:" + item.getStatus());
                    super.onNext(item);
                }
            };
//                    执行下载命令
            try {
                pullImageCmd
                        .exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
                throw new RuntimeException(e);
            }

            System.out.println("下载完成");
        }


//
//       将镜像创建为容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);

//          创建容器时,可以指定文件路径(Volumn)映射, 作用是把本地的文件同步到容器中,可以让容器访问.
        HostConfig hostConfig = new HostConfig();
//          设置内存
        hostConfig.withMemory(1000 * 1000 * 100l);
        hostConfig.withMemorySwap(0l);
        hostConfig.withCpuCount(1l);
        hostConfig.setBinds(new Bind(codeFile.getParentFile().getAbsolutePath(), new Volume("/app")));
//          创建容器
        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)
                .withReadonlyRootfs(true)
                .withAttachStdin(true)
                .withAttachStderr(true)
                .withAttachStdout(true)
                .withTty(true)
//                加上下面这一行会不能之久运行
//                .withCmd("echo", "Hello Docker")
                .exec();
//        获取执行容器的id
        String containerId = createContainerResponse.getId();
//        启动容器执行代码
        dockerClient.startContainerCmd(containerId).exec();

//        docker exec 容器名称 java -cp /app Main 1 2
//        执行命令 并获取结果

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String input : inputList) {
            StopWatch stopWatch = new StopWatch();

            String[] strings = input.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, strings);
            ExecCreateCmdResponse execCreateCmdResponsec = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();

            log.info("创建执行命令: " , execCreateCmdResponsec);
//            System.out.println("创建执行命令: " + execCreateCmdResponsec);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            long time = 0l;
            final int[] exitValue = {0};
            final boolean[] timeout = {true};

            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        exitValue[0] = -1;
                        System.out.println("输出错误结果: " + new String(frame.getPayload()));
                    } else {
                        String s = new String(frame.getPayload());
                        String replace = null;
                        if (s.contains("\n")){
                            replace = s.replace("\n", "");
                            if (StrUtil.isNotBlank(replace)){
                                message[0] = replace;
                                System.out.println("输出结果: " + replace );
                            }
                        }else{
                            message[0] = s;
                            System.out.println("输出结果: " + s );
                        }

                    }
                    super.onNext(frame);
                }
            };
            final long[] maxMemory = {0l};
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(Statistics object) {
                    System.out.println("内存占用" + object.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(object.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            });
            statsCmd.exec(statisticsResultCallback);

            try {
                stopWatch.start();
                dockerClient.execStartCmd(execCreateCmdResponsec.getId())
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setExitValue(exitValue[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);

        }
        CompletableFuture.runAsync(() -> {
            dockerClient.stopContainerCmd(containerId).exec();
            dockerClient.removeContainerCmd(containerId).exec();
        });

        return executeMessageList;
    }




}
